package com.etc.controller.user;

import com.etc.common.ServiceException;
import com.etc.common.SessionConst;
import com.etc.po.Login;
import com.etc.service.user.IUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    IUserService service;

    @PostMapping("login")
    public String login(Login login, HttpSession session, HttpServletRequest request, Model model) {

        Login loginpo = null;
        try {
            loginpo = service.findByLoginUname(login);
            session.setAttribute(SessionConst.USER_INFO, loginpo);

        } catch (ServiceException e) {
            logger.debug("登録失敗しました");

            //　i18N wapper 処理
            RequestContext requestContext=new RequestContext(request);
            model.addAttribute("msg", requestContext.getMessage(e.getMessage()));
            return "login";

        }

        return "forward:th_main.action";
    }

    /**
     * 分页查询
     * 第二页请求
     * http://localhost:8080/list.action?pageNo=2
     * 第三页请求
     * http://localhost:8080/list.action
     */
    @RequestMapping(value="/list",method= RequestMethod.GET)
    @ResponseBody
    public PageInfo<Login> pageList(ModelMap map, @RequestParam(defaultValue="1",required=true,value="pageNo") Integer pageNo){
        Integer pageSize=10;//每页显示记录数
        //分页查询
        PageHelper.startPage(pageNo, pageSize);
        List<Login> userList = service.list();//获取所有用户信息
        PageInfo<Login> pageInfo=new PageInfo<Login>(userList);
        return pageInfo;
    }
}
